package com.example.yhmap_outline;

import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpHost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.stereotype.Component;

/**
 * 2022/8/23
 *
 * @author fengyu
 */
@Component
public class HttpPooling {
    private final Map<String, CloseableHttpClient> poolings = new HashMap<>();

    private static final int MAX_CONN = Integer.MAX_VALUE; // 最大连接数

    private static final int DEFAULT_PRE_ROUTE = 200;

    private static final int MAX_ROUTE = 200;

    public CloseableHttpClient getHttpClient(String host, int port){
        String key = host + ":" + port;
        if (poolings.containsKey(key)) {
            return poolings.get(key);
        }
        synchronized (poolings){
            if (!poolings.containsKey(key)) {
                PoolingHttpClientConnectionManager pm = new PoolingHttpClientConnectionManager();
                pm.setDefaultMaxPerRoute(DEFAULT_PRE_ROUTE);
                pm.setMaxTotal(MAX_CONN);
                pm.setMaxPerRoute(new HttpRoute(new HttpHost(host, port)), MAX_ROUTE);
                poolings.put(key, HttpClients.custom().setConnectionManager(pm).build());
            }
        }
        return poolings.get(key);
    }
}
